const {
  Article,
  AdminUser,
  About,
  FriendshipLinks,
  Timeline,
  Visitors,
  LeaveMessages,
  Tag,
} = require("./db");

const express = require("express");
// 请求转发
const request = require("request");
const app = express();
app.use(require("cors")());
app.use(express.json());
app.use("/uploads", express.static(__dirname + "/uploads"));

const secret = "1q2w3e4r5t6y7u8i9o";

// 请求转发
// 01.discovery

// 轮播图
app.get("/api/banner", function (req, res, next) {
  var url = "https://autumnfish.cn/banner";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 推荐歌单
app.get("/api/personalized", function (req, res, next) {
  var url = "https://autumnfish.cn/personalized";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 最新音乐
app.get("/api/personalized/newsong", function (
  req,
  res,
  next
) {
  var url = "https://autumnfish.cn/personalized/newsong";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 最新mv
app.get("/api/personalized/mv", function (
  req,
  res,
  next
) {
  var url = "https://autumnfish.cn/personalized/mv";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 播放歌曲
app.get("/api/https://autumnfish.cn/song/url", function (req, res, next) {
  var url = "https://autumnfish.cn/song/url";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      // var data = JSON.parse(body);
      res.send("成功");
    } else {
      res.send("{error:404}");
    }
  });
});

// 02.playlists
// 顶部精品歌单
app.get(
  "/api/https://autumnfish.cn/top/playlist/highquality",
  function (req, res, next) {
    var url = "https://autumnfish.cn/top/playlist/highquality";
    request(url, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        var data = JSON.parse(body);
        res.send(data);
      } else {
        res.send("{error:404}");
      }
    });
  }
);
// 歌单列表
app.get("/api/https://autumnfish.cn/top/playlist/", function (req, res, next) {
  var url = "https://autumnfish.cn/top/playlist/";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});

// 03.songs
// 歌曲列表
app.get("/api/https://autumnfish.cn/top/song", function (req, res, next) {
  var url = "https://autumnfish.cn/top/song";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});

// 04.mvs
// mv列表
app.get("/api/https://autumnfish.cn/mv/all", function (req, res, next) {
  var url = "https://autumnfish.cn/mv/all";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});

// 05.result
// 搜索
app.get("/api/https://autumnfish.cn/search", function (req, res, next) {
  var url = "https://autumnfish.cn/search";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});

// 06.playlist
// 获取歌单
app.get("/api/https://autumnfish.cn/playlist/detail", function (
  req,
  res,
  next
) {
  var url = "https://autumnfish.cn/playlist/detail";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 获取热门评论
app.get("/api/https://autumnfish.cn/comment/hot", function (req, res, next) {
  var url = "https://autumnfish.cn/comment/hot";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 获取最新评论
app.get("/api/https://autumnfish.cn/comment/playlist", function (
  req,
  res,
  next
) {
  var url = "https://autumnfish.cn/comment/playlist";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});

// 07.mv
// 获取mv地址
app.get("/api/https://autumnfish.cn/mv/url", function (req, res, next) {
  var url = "https://autumnfish.cn/mv/url";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 获取相关mv
app.get("/api/https://autumnfish.cn/simi/mv", function (req, res, next) {
  var url = "https://autumnfish.cn/simi/mv";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 获取mv信息
app.get("/api/https://autumnfish.cn/mv/detail", function (req, res, next) {
  var url = "https://autumnfish.cn/mv/detail";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 获取评论数据
app.get("/api/https://autumnfish.cn/comment/mv", function (req, res, next) {
  var url = "https://autumnfish.cn/comment/mv";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});
// 获取歌手信息
app.get("/api/https://autumnfish.cn/artists", function (req, res, next) {
  var url = "https://autumnfish.cn/artists";
  request(url, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      var data = JSON.parse(body);
      res.send(data);
    } else {
      res.send("{error:404}");
    }
  });
});

//管理员
// 新建管理员
app.post("/api/admin_users", async (req, res) => {
  const model = await AdminUser.create(req.body);
  res.send(model);
});
// 管理员列表
app.get("/api/admin_users", async (req, res) => {
  const model = await AdminUser.find();
  res.send(model);
});
//管理员详情
app.get("/api/admin_users/:id", async (req, res) => {
  const model = await AdminUser.findById(req.params.id);
  res.send(model);
});
// 删除管理员
app.delete("/api/admin_users/:id", async (req, res) => {
  const model = await AdminUser.findByIdAndDelete(req.params.id);
  res.send(model);
});
// 修改管理员
app.put("/api/admin_users/:id", async (req, res) => {
  const model = await AdminUser.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});
// 登录
app.post("/api/login", async (req, res) => {
  const user = await AdminUser.findOne({
    username: req.body.username,
  }).select("+password");

  if (!user) {
    return res.status(422).send({
      message: "用户名不存在",
    });
  }
  const isValid = require("bcrypt").compareSync(
    req.body.password,
    user.password
  );
  if (!isValid) {
    return res.status(422).send({
      message: "密码错误",
    });
  }
  // 生成token
  const jwt = require("jsonwebtoken");
  const token = jwt.sign({ id: user._id }, secret);
  res.send(token);
});
//注册
app.post("/api/register", async (req, res) => {
  const model = await AdminUser.create({
    username: req.body.username,
    password: req.body.password,
  });
  res.send(model);
});

// 关于
// 新增个人信息
app.post("/api/about", async (req, res) => {
  const model = await About.create(req.body);
  res.send(model);
});
// 获取个人信息列表
app.get("/api/about", async (req, res) => {
  const model = await About.find();
  res.send(model);
});
// 个人信息详情
app.get("/api/about/:id", async (req, res) => {
  const model = await About.findById(req.params.id);
  res.send(model);
});
// 修改保存个人信息
app.put("/api/about/:id", async (req, res) => {
  const model = await About.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});
// 删除个人信息
app.delete("/api/about/:id", async (req, res) => {
  const model = await About.findByIdAndDelete(req.params.id);
  res.send(model);
});

// 友链
app.post("/api/friendship", async (req, res) => {
  const model = await FriendshipLinks.create(req.body);
  res.send(model);
});
app.get("/api/friendship", async (req, res) => {
  const model = await FriendshipLinks.find();
  res.send(model);
});
app.get("/api/friendship/:id", async (req, res) => {
  const model = await FriendshipLinks.findById(req.params.id);
  res.send(model);
});
app.put("/api/friendship/:id", async (req, res) => {
  const model = await FriendshipLinks.findByIdAndUpdate(
    req.params.id,
    req.body
  );
  res.send(model);
});
app.delete("/api/friendship/:id", async (req, res) => {
  const model = await FriendshipLinks.findByIdAndDelete(req.params.id);
  res.send(model);
});

// 时间线
app.post("/api/timeline", async (req, res) => {
  const model = await Timeline.create(req.body);
  res.send(model);
});
app.get("/api/timeline", async (req, res) => {
  const model = await Timeline.find();
  model.reverse();
  res.send(model);
});
app.get("/api/timeline/:id", async (req, res) => {
  const model = await Timeline.findById(req.params.id);
  res.send(model);
});
app.put("/api/timeline/:id", async (req, res) => {
  const model = await Timeline.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});
app.delete("/api/timeline/:id", async (req, res) => {
  const model = await Timeline.findByIdAndDelete(req.params.id);
  res.send(model);
});

// 发表留言的游客
app.post("/api/visitors", async (req, res) => {
  const model = await Visitors.insertMany(req.body);
});

// 获取留言
app.get("/api/leaveMessages", async (req, res) => {
  let leaveMessages = await LeaveMessages.find();
  leaveMessages.reverse();
  if (req.query.page) {
    //前端传入了page则做分页处理，不传就不做分页处理
    const page = req.query.page; //拿到传入的page,要用query拿
    leaveMessages = leaveMessages.slice((page - 1) * 20, page * 20); //分页处理
  }
  res.send(leaveMessages);
});
// //  更新留言
// app.put('/api/leaveMessages', async (req, res) => {  //更新留言（回复/删除）
//     // req.body.reverse()  //拿的时候对留言反序了的，那么更新留言的时候要掰过来
//     await LeaveMessages.remove()
//     await LeaveMessages.insertMany(req.body)
//     res.send('更新成功')
// })
// 增加留言
app.post("/api/leaveMessages", async (req, res) => {
  await LeaveMessages.insertMany(req.body);
  let messages = await LeaveMessages.find();
  messages.reverse();
  res.send(messages);
});
// 留言详情
app.get("/api/leaveMessages/:id", async (req, res) => {
  const model = await LeaveMessages.findById(req.params.id);
  res.send(model);
});
// 更新保存留言
app.put("/api/leaveMessages/:id", async (req, res) => {
  const model = await LeaveMessages.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});
// 删除留言
app.delete("/api/leaveMessages/:id", async (req, res) => {
  const model = await LeaveMessages.findByIdAndDelete(req.params.id);
  res.send(model);
});

//新增文章
app.post("/api/articles", async (req, res) => {
  const model = await Article.create(req.body);
  res.send(model);
});

// 文章列表
app.get("/api/articles", async (req, res) => {
  let model = await Article.find().populate("tags");
  if (req.query.page) {
    //前端传入了page则做分页处理，不传就不做分页处理
    const total = model.length;
    const page = req.query.page; //拿到传入的page,要用query拿
    model = model.slice((page - 1) * 5, page * 5); //分页处理
    model.push(total);
  }
  // const total = model.length
  // const page = req.query.page
  // model = model.slice((page - 1) * 5, page * 5)  //分页处理
  // model.push(total)  //传出文章总数
  res.send(model);
});

//文章详情
app.get("/api/articles/:id", async (req, res) => {
  const model = await Article.findById(req.params.id).populate("tags");
  res.send(model);
});
// 修改保存
app.put("/api/articles/:id", async (req, res) => {
  const model = await Article.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});

// 删除
app.delete("/api/articles/:id", async (req, res) => {
  const model = await Article.findByIdAndDelete(req.params.id);
  res.send(model);
});

// 标签

//新增标签
app.post("/api/tags", async (req, res) => {
  const model = await Tag.create(req.body);
  res.send(model);
});

// 标签列表
app.get("/api/tags", async (req, res) => {
  const model = await Tag.find();
  res.send(model);
});

//标签详情
app.get("/api/tags/:id", async (req, res) => {
  const model = await Tag.findById(req.params.id);
  res.send(model);
});
// 修改保存
app.put("/api/tags/:id", async (req, res) => {
  const model = await Tag.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});

// 删除标签
app.delete("/api/tags/:id", async (req, res) => {
  const model = await Tag.findByIdAndDelete(req.params.id);
  res.send(model);
});

// 文件上传接口
const multer = require("multer");
const upload = multer({ dest: __dirname + "/uploads" });
app.post("/api/upload", upload.single("file"), async (req, res) => {
  const file = req.file;
  file.url = `http://localhost:3000/uploads/${file.filename}`;
  res.send(file);
});

app.listen(3000, async (req, res) => {
  console.log("app is running at port 3000");
});
